package com.kehongborui.empmanagesys.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-20
 */
@WebFilter( urlPatterns = {"*.html"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String errorPage = filterConfig.getInitParameter("errorPage");
    }

    /**
     * 过滤 servletRequest servletResponse
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取路径
        // 2. 根据路径判断是获取登录页面，还是获取非登录页面的其他资源
        // 2.1 如果登录页面，就直接放行，否则判断用户是否登录，登录成功才能继续向servlet 获取资源，否则重定向到 login.html
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String uri = request.getRequestURI();

        if (!uri.contains("login") && request.getSession().getAttribute("LOGIN_USER") == null) {
            response.sendRedirect("login.html");
        } else {
            // 捕获异常，并重定向到页面
            try {
//                Error404ResponseWrapper responseWrapper = new Error404ResponseWrapper(response);

                // 放行
                filterChain.doFilter(servletRequest, response);
//                filterChain.doFilter(servletRequest, responseWrapper);
//                if (!responseWrapper.isFound()) {
//                    response.sendRedirect("404.jsp");
//                    return;
//                }
            } catch (RuntimeException e) {
                response.sendRedirect("error.jsp");
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
